﻿/*
 * Autore: Paolo Farina
 */

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.Win32;
using RecipesManager.Data;
using RecipesManager.Data.Operations;
using RecipesManager.MainControls.ShopListSubControls;
using Application = System.Windows.Application;
using ButtonBase = System.Windows.Controls.Primitives.ButtonBase;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using ListView = System.Windows.Controls.ListView;
using MenuItem = System.Windows.Controls.MenuItem;
using MessageBox = System.Windows.MessageBox;
using UserControl = System.Windows.Controls.UserControl;

namespace RecipesManager.MainControls
{


    public class ShopListElems
    {
        public ShopListElems(string name, string qt, string udm)
        {
            
            Name = name;
            Qt = qt;
            UdM = udm;
        }

        
        public string Name { get; set; }
        public string Qt { get; set; }
        public string UdM { get; set; }


        // override object.Equals
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }
            return ((ShopListElems)obj).Name.Equals(this.Name) && ((ShopListElems)obj).UdM.Equals(this.UdM);
        }

        //TODO mi sembra che questo non sia un metodo corretto per calcolare il hashcode.. da confermare
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }

    /// <summary>
    /// Logica di interazione per ShopListUserControl.xaml
    /// </summary>
    public partial class ShopListUserControl : UserControl, IMyUserControls, ISwitchable
    {
        ShopListMainPane _actualPanel;
        ObservableCollection<ShopListElems> shopListElems = null;

        public ShopListUserControl()
        {
            InitializeComponent();
            shopListElems=new ObservableCollection<ShopListElems>();
            Refresh_ShopList_List();
            lw_shopList.ItemsSource = shopListElems;
            bt_delete.IsEnabled = false;

            CommandManager.RegisterClassCommandBinding(typeof(ShopListUserControl), _savebinding);
            CommandManager.RegisterClassCommandBinding(typeof(ShopListUserControl), _closebinding);
        }


        public bool Save_Context()
        {
            if (_actualPanel != null && _actualPanel.bt_salva.IsEnabled)
            {
                var result = MessageBox.Show((string)Application.Current.FindResource("want_to_save"),
                                             (string)Application.Current.FindResource("notification_dialog_type"),
                                             MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
                        var resSave=_actualPanel.Save();
                        if (!resSave) _actualPanel.bt_salva.IsEnabled = false;
                        Refresh_ShopList_List(_actualPanel.tb_title.Text);
                        if (!resSave) _actualPanel.bt_salva.IsEnabled = true;
                        Mouse.OverrideCursor = null;
                        break;
                    case MessageBoxResult.No:
                        break;
                    case MessageBoxResult.Cancel:
                        return false;
                }
            }
            return true;
        }

        void Refresh_ShopList_List(string id = "")
        {
            lw_shopList.SelectedItem = null;
            var count = lw_shopList.Items.Count;

            shopListElems.Clear();            
            foreach (var e in Manager.ShoppingList) 
                if (e.Name.ToLower().Contains(tb_search.Text.ToLower()))
                    shopListElems.Add(new ShopListElems(e.Name, e.FormattedQuantity, e.Measure.Name));

            if (id!=null && !id.Equals("")) lw_shopList.SelectedItem = id;
        }

        void Close_Context()
        {
            if (_actualPanel != null && _actualPanel.bt_salva.IsEnabled)
            {
                var result = MessageBox.Show((string)Application.Current.FindResource("want_to_save_before_closing"),
                                             (string)Application.Current.FindResource("notification_dialog_type"),
                                             MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        _actualPanel.Save();
                        _actualPanel = null;
                        eventContentPane.Content = _actualPanel;
                        bt_delete.IsEnabled = false;
                        lw_shopList.SelectedItem = null;
                        Refresh_ShopList_List();
                        break;
                    case MessageBoxResult.No:
                        _actualPanel = null;
                        eventContentPane.Content = _actualPanel;
                        bt_delete.IsEnabled = false;
                        lw_shopList.SelectedItem = null;
                        break;
                    case MessageBoxResult.Cancel:
                        break;
                }
            }
            else
            {
                _actualPanel = null;
                eventContentPane.Content = _actualPanel; 
                bt_delete.IsEnabled = false;
                lw_shopList.SelectedItem = null;
            }
        }

        public bool CheckShopListOnDelete(string id, string measeure)
        {
            IEnumerable<string> canDeleteMessage;

            var canDelete = Operations.CanRemoveIngredientFromList(id, measeure, out canDeleteMessage);
            var msgFromCanRemove = canDeleteMessage.Aggregate("", (current, m) => current + (Environment.NewLine + m));
            var msgStr = "";


            if (canDelete)
            {
                msgStr += (string)Application.Current.FindResource("ElementCanBeDeleted");
                if (!msgFromCanRemove.Equals("")) msgStr += " " + (string)Application.Current.FindResource("ElementIsUsedBy") + msgFromCanRemove;

                var dresult = MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.YesNo, MessageBoxImage.Warning);

                switch (dresult)
                {
                    case MessageBoxResult.Yes:
                        return true;
                    case MessageBoxResult.No:
                        return false;
                }
            }
            else
            {
                msgStr = (string)Application.Current.FindResource("ElementCannotBeDeleted") + msgFromCanRemove;
                MessageBox.Show(msgStr, (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }


        #region ButtonHandlers

        public void Bt_Back_Click(object sender, RoutedEventArgs e)
        {
            if (Save_Context()) Switcher.Switch(new MainMenu());
        }

        public void Bt_Delete_Click(object sender, RoutedEventArgs e)
        {
            if (lw_shopList.SelectedValue != null && CheckShopListOnDelete(((ShopListElems)lw_shopList.SelectedValue).Name, ((ShopListElems)lw_shopList.SelectedValue).UdM))
            {
                Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
                Manager.ShoppingList.Remove(((ShopListElems)lw_shopList.SelectedValue).Name, ((ShopListElems)lw_shopList.SelectedValue).UdM);
                Refresh_ShopList_List();
                eventContentPane.Content = null;
                _actualPanel = null;
                Mouse.OverrideCursor = null;
            }
        }

        public void Bt_Stamp_Click(object sender, RoutedEventArgs e)
        {
            if (Data.Manager.ShoppingList.Count == 0)
            {
                MessageBox.Show("Lista vuota!", (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            var dialog = new SaveFileDialog();
            dialog.FileName = "Lista_della_Spesa";
            dialog.DefaultExt = ".html";
            dialog.Filter = "HTML|*.html";

            var result = dialog.ShowDialog();

            if(result!=true)return;

            File.WriteAllText(dialog.FileName, Data.Manager.ShoppingList.ToHtml());
            MessageBox.Show("Lista Salvata Correttamente!", (string)Application.Current.FindResource("notification_dialog_type"), MessageBoxButton.OK, MessageBoxImage.Information);
        }

        public void Bt_Add_Click(object sender, RoutedEventArgs e)
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            if (_actualPanel != null && !Save_Context()) return;
            this.eventContentPane.Content = new ShopListMainPane("","");
            _actualPanel = (ShopListMainPane)eventContentPane.Content;
            Mouse.OverrideCursor = null;
        }

        public void Bt_Search_Click(object sender, RoutedEventArgs e)
        {
            Refresh_ShopList_List();
        }

        public void Bt_Clear_Search_Click(object sender, RoutedEventArgs e)
        {
            tb_search.Text = "";
            Refresh_ShopList_List();
        }

        public void Lb_Items_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            var list = (ListView)sender;
            bt_delete.IsEnabled = list.SelectedItem != null;
            if (!Save_Context() || list.SelectedValue == null) { Mouse.OverrideCursor = null; return; }
            _actualPanel = new ShopListMainPane(((ShopListElems)list.SelectedValue).Name, ((ShopListElems)list.SelectedValue).UdM);
            eventContentPane.Content = _actualPanel;
            Mouse.OverrideCursor = null;
        }

        public string SectionName
        {
            get { throw new NotImplementedException(); }
        }

        void Tb_search_OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter) return;
            e.Handled = true;
            bt_search.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
        }

        #endregion

        #region OtherHandlers

        private void Lw_Eventi_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var listView = sender as ListView;
            if (listView == null)
                return;

            var gridView = listView.View as GridView;
            if (gridView == null)
                return;

            var workingWidth = listView.ActualWidth - SystemParameters.VerticalScrollBarWidth;

            if (listView.Equals(lw_shopList))
            {
                var col1 = 0.50;
                var col2 = 0.25;
                var col3 = 0.25;

                gridView.Columns[0].Width = workingWidth * col1;
                gridView.Columns[1].Width = workingWidth * col2;
                gridView.Columns[2].Width = workingWidth * col3;

            }
        }

        private void sl_dim_ValueChanged(object sender, RoutedEventArgs e)
        {
            var sl = (MenuItem)sender;

            if (sl.Name.EndsWith("Dim"))
            {
                zoomAum.IsEnabled = true;
                FontSize = FontSize - 2;
                if (FontSize <= 10)
                {
                    zoomDim.IsEnabled = false;
                }
            }
            else
            {
                zoomDim.IsEnabled = true;
                FontSize = FontSize + 2;
                if (FontSize >= 22)
                {
                    zoomAum.IsEnabled = false;
                }
            }


        }

        #endregion

        #region ISwitchable Members

        public void UtilizeState(object state)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region SaveCommandRegion

        readonly CommandBinding _savebinding = new CommandBinding(ApplicationCommands.Save, CommandSaveHandler);

        static void CommandSaveHandler(object target, ExecutedRoutedEventArgs e)
        {
            var id = (ShopListElems)((ShopListUserControl)target).lw_shopList.SelectedItem;
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            ((ShopListUserControl)target)._actualPanel.Save();
            ((ShopListUserControl)target).Refresh_ShopList_List(((ShopListUserControl)target)._actualPanel.tb_title.Text);
            Mouse.OverrideCursor = null;
        }

        #endregion

        #region CloseCommandRegion

        readonly CommandBinding _closebinding = new CommandBinding(ApplicationCommands.Close, CommandCloseHandler);

        static void CommandCloseHandler(object target, ExecutedRoutedEventArgs e)
        {

            ((ShopListUserControl)target).Close_Context();
        }

        #endregion

        
    }
}
